package com.badboy.mycarbon.system.service.impl;

import com.badboy.mycarbon.system.entity.SysDict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.badboy.mycarbon.system.entity.SysDict;
import com.badboy.mycarbon.system.entity.SysDictItem;
import com.badboy.mycarbon.system.entity.query.SysDictItemQuery;
import com.badboy.mycarbon.system.entity.query.SysDictQuery;
import com.badboy.mycarbon.system.entity.vo.PageVO;
import com.badboy.mycarbon.system.mapper.SysDictItemMapper;
import com.badboy.mycarbon.system.mapper.SysDictMapper;
import com.badboy.mycarbon.system.service.SysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 系统字典Service实现类
 */

@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Autowired
    private SysDictMapper sysDictMapper;

    @Autowired
    private SysDictItemMapper sysDictItemMapper;

    @Override
    public PageVO<SysDict> getSysDictPageList(SysDictQuery query) {
        Page<SysDict> page = new Page<>(query.getCurrent(), query.getSize());
        LambdaQueryWrapper<SysDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDict::getDelFlag, 0);
        if (query.getDictCode() != null && !query.getDictCode().isEmpty()) {
            wrapper.like(SysDict::getDictCode, query.getDictCode());
        }
        if (query.getDictName() != null && !query.getDictName().isEmpty()) {
            wrapper.like(SysDict::getDictName, query.getDictName());
        }
        IPage<SysDict> pageResult = page(page, wrapper);

        // 如果 PageVO 没有带参数的构造函数，使用手动赋值
        PageVO<SysDict> pageVO = new PageVO<>();
        pageVO.setRecords(pageResult.getRecords());
        pageVO.setTotal(pageResult.getTotal());
        pageVO.setCurrent(pageResult.getCurrent());
        pageVO.setSize(pageResult.getSize());

        return pageVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysDict(SysDict sysDict) {
        // 检查字典码是否已存在（逻辑未删除）
        LambdaQueryWrapper<SysDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDict::getDictCode, sysDict.getDictCode())
                .eq(SysDict::getDelFlag, 0);
        if (getOne(wrapper) != null) {
            throw new RuntimeException("字典码已存在");
        }
        save(sysDict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysDict(Long id) {
        SysDict sysDict = getById(id);
        if (sysDict == null || sysDict.getDelFlag() == 1) {
            throw new RuntimeException("字典不存在");
        }
        // 逻辑删除：标记为已删除
        sysDict.setDelFlag(1);
        updateById(sysDict);
    }


    @Override
    public List<SysDict> getAllDict() {
        return sysDictMapper.getAllDict();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByCode(SysDict sysDict) {
        SysDict existDict = getById(sysDict.getId());
        if (existDict == null) {
            throw new RuntimeException("字典不存在");
        }
        // 检查新字典码是否已被其他字典使用（逻辑未删除）
        LambdaQueryWrapper<SysDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDict::getDictCode, sysDict.getDictCode())
                .eq(SysDict::getDelFlag, 0)
                .ne(SysDict::getId, sysDict.getId());
        if (getOne(wrapper) != null) {
            throw new RuntimeException("字典码已存在");
        }
        updateById(sysDict);
    }

    @Override
    public PageVO<SysDictItem> getSysDictItemPageList(SysDictItemQuery query) {
        PageVO<SysDictItem> pageVO = new PageVO<>();
        LambdaQueryWrapper<SysDictItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictItem::getDictCode, query.getDictCode())
                .orderByAsc(SysDictItem::getSortOrder); // 使用 sort_order 排序
        if (query.getItemValue() != null && !query.getItemValue().isEmpty()) {
            wrapper.like(SysDictItem::getItemValue, query.getItemValue());
        }
        if (query.getItemCh() != null && !query.getItemCh().isEmpty()) {
            wrapper.like(SysDictItem::getItemCh, query.getItemCh());
        }
        if (query.getStatus() != null) {
            wrapper.eq(SysDictItem::getStatus, query.getStatus());
        }
        // 使用 MyBatis-Plus 自带的分页方法
        Page<SysDictItem> page =
                new Page<>(query.getCurrent(), query.getSize());
        page = sysDictItemMapper.selectPage(page, wrapper);

        pageVO.setRecords(page.getRecords());
        pageVO.setTotal(page.getTotal());
        pageVO.setCurrent(page.getCurrent());
        pageVO.setSize(page.getSize());
        return pageVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addSysDictItem(SysDictItem sysDictItem) {
        // 检查父字典是否存在
        LambdaQueryWrapper<SysDict> dictWrapper = new LambdaQueryWrapper<>();
        dictWrapper.eq(SysDict::getDictCode, sysDictItem.getDictCode())
                .eq(SysDict::getDelFlag, 0);
        SysDict dict = getOne(dictWrapper);
        if (dict == null) {
            throw new RuntimeException("字典码不存在");
        }

        // 设置默认值
        if (Objects.isNull(sysDictItem.getSortOrder())) {
            sysDictItem.setSortOrder(0);
        }

        // 插入并获取ID
        sysDictItemMapper.insert(sysDictItem);

        // 验证插入结果
        SysDictItem inserted = sysDictItemMapper.selectById(sysDictItem.getId());
        if (inserted == null) {
            throw new RuntimeException("插入失败，无法获取插入的记录");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysDictItemById(SysDictItem sysDictItem) {
        if (sysDictItem.getId() == null) {
            throw new RuntimeException("字典项ID不能为空");
        }
        SysDictItem existItem = sysDictItemMapper.selectById(sysDictItem.getId());
        if (existItem == null) {
            throw new RuntimeException("字典项不存在");
        }

        // 检查同字典下是否存在相同的 itemValue
        LambdaQueryWrapper<SysDictItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictItem::getDictCode, sysDictItem.getDictCode())
                .eq(SysDictItem::getItemValue, sysDictItem.getItemValue())
                .ne(SysDictItem::getId, sysDictItem.getId());
        SysDictItem sameCodeItem = sysDictItemMapper.selectOne(wrapper);
        if (sameCodeItem != null) {
            throw new RuntimeException("字典项值已存在");
        }

        sysDictItemMapper.updateById(sysDictItem);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeSysDictItemById(Long id) {
        // 直接物理删除，因为没有 del_flag 列
        sysDictItemMapper.deleteById(id);
    }

    @Override
    public List<SysDictItem> getNameMapByCode(String dictCode) {
        LambdaQueryWrapper<SysDictItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictItem::getDictCode, dictCode)
                .orderByAsc(SysDictItem::getSortOrder); // 使用 sort_order 排序
        return sysDictItemMapper.selectList(wrapper);
    }

    @Override
    public List<SysDictItem> getCityDict() {
        LambdaQueryWrapper<SysDictItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictItem::getDictCode, "CITY_CODE")
                .orderByAsc(SysDictItem::getSortOrder); // 使用 sort_order 排序
        return sysDictItemMapper.selectList(wrapper);
    }

    @Override
    public List<SysDictItem> getFieldDict() {
        LambdaQueryWrapper<SysDictItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictItem::getDictCode, "FIELD_CODE")
                .orderByAsc(SysDictItem::getSortOrder); // 使用 sort_order 排序
        return sysDictItemMapper.selectList(wrapper);
    }
}